package com.nothingboard.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nothingboard.common.data.request.GlobalVariables;
import com.nothingboard.module.code.service.CodeService;
import com.nothingboard.module.member.model.MemberLogonDto;
import com.nothingboard.module.member.service.MemberService;
import com.nothingboard.module.site.model.SiteConfigDto;
import com.nothingboard.module.site.service.SiteConfigService;

@Controller
@RequestMapping(value="admin")
public class DefaultController {
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private SiteConfigService siteConfigService;
	
	private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);
	
	@RequestMapping({"/", "/index"})
	public String rootPage(HttpServletRequest request, ModelMap model) throws Exception {

		return "admin/main";
	}
	
	@RequestMapping({"/login/", "/login/index"})
	public String login(HttpServletRequest request, ModelMap model) throws Exception {

		return "admin/member/logon";
	}
	
	@RequestMapping(value="/login/submit")
	public void loginProc(MemberLogonDto dto, HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap model)
			throws Exception {
		
		String domain = request.getLocalName();
		String redirect = request.getContextPath() + GlobalVariables.ADMIN_LOGIN_PAGE;
		
		SiteConfigDto siteConfigDto = (SiteConfigDto) siteConfigService.getSiteConfig(domain);
		if(siteConfigDto != null) {
			dto.setSiteNo(siteConfigDto.getSiteNo());
		}

		if(session == null) session = request.getSession(false);

		if(memberService.getLoginCheck(dto,session)){
			redirect = request.getContextPath() + GlobalVariables.ADMIN_MAIN_PAGE;
		}
		logger.debug("redirect page is " + redirect);
		
		response.sendRedirect(redirect);
	}

}
